﻿using System;
using System.Linq;

using VSTalk.Engine.Core.EntitySession;
using VSTalk.Engine.Core.XmppConnection;
using VSTalk.Model;

using agsXMPP.protocol.x.muc;

namespace VSTalk.Engine.Core.XmppCommunication.Services.RoomManager
{
    public class RoomManager : BaseCommunicationService, IRoomManager
    {
        private MucManager _mucManager;

        public override void Initialize(IClientConnection connection)
        {
            base.Initialize(connection);
            _mucManager = new MucManager(Connection);
        }

        public void AddRoom(IRoomInfo roomInfo)
        {
            var room = InitRoom(roomInfo);
            Client.Rooms.Add(room);
        }

        public void DeleteRoom(Guid roomId)
        {
            var target = Client.Rooms.First(room => room.Id == roomId);
            LeaveRoom(roomId);
            Client.Rooms.Remove(target);
        }

        public void JoinRoom(Guid roomId)
        {
            if (ClientContext.State != ClientState.Connected)
            {
                return;
            }
            var target = Client.Rooms.First(room => room.Id == roomId);
            var context = GetContext(target);
            var jid = XmppUtils.XmppIdConverter.Jid(target);
            _mucManager.JoinRoom(jid, target.Nickname);
            context.IsActive = true;
        }

        private static IRoomContext GetContext(Room target)
        {
            return AppServices.Get<ISessionModel>().GetRoomContext(target);
        }

        public void LeaveRoom(Guid roomId)
        {
            var target = Client.Rooms.First(room => room.Id == roomId);
            var jid = XmppUtils.XmppIdConverter.Jid(target);
            var context = GetContext(target);
            if (context.IsActive)
            {
                _mucManager.LeaveRoom(jid, target.Nickname);
                context.IsActive = false;
            }
        }

        private Room InitRoom(IRoomInfo roomInfo)
        {
            Room room = new Room();

            room.Id = Guid.NewGuid();
            room.Name = roomInfo.RoomName;
            room.Server = roomInfo.Server;
            room.Nickname = roomInfo.Nickname;
            return room;
        }
    }
}